import { useState, useEffect, useRef } from 'react'

const Demo6 = () => {
  const inputRef = useRef(null)
  const [comments, setComments] = useState([
    { id: 1, title: '精彩' },
    { id: 2, title: '很好' },
  ])

  useEffect(() => {
    inputRef.current.focus()
  }, [])

  const publishContent = () => {
    let content = inputRef.current.value
    let comment = { id: Date.now(), title: content }
    setComments([comment, ...comments])
    inputRef.current.value = ''
  }

  const del = (id) => {
    let newComments = comments.filter((item) => item.id !== id)
    setComments(newComments)
  }

  return (
    <>
      <h3 className="m-1 f-c-c">发布删除评论案例</h3>
      <div className="header">
        <input type="text" ref={inputRef} />
        <button onClick={publishContent}>发布</button>
      </div>
      <ul>
        {comments.map((item) => {
          return (
            <li className="flex flex-justify-between" key={item.id}>
              <span>{item.title}</span>
              <a
                href="#"
                onClick={() => {
                  del(item.id)
                }}
              >
                删除
              </a>
            </li>
          )
        })}
      </ul>
      {comments.length === 0 && <p>暂无数据</p>}
    </>
  )
}

export default Demo6
